﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RoadFlow.Utility;
using System.IO;
using Newtonsoft.Json.Linq;

namespace RoadFlow.Mvc.Areas.RoadFlowCore.Controllers
{
    [Area("RoadFlowCore")]
    public class UserFileController : Controller
    {
        [Validate(CheckApp = false)]
        public IActionResult Index()
        {
            Guid userId = Current.UserId;
            if (userId.IsEmptyGuid())
            {
                userId = Current.EnterpriseWeiXinUserId;
            }
            ViewData["queryString"] = Request.UrlQuery();
            ViewData["id"] = new Business.UserFile().GetUserRoot(userId).DESEncrypt();
            ViewData["isselect"] = Request.Querys("isselect");//是否是选择附件
            ViewData["ismobile"] = Request.Querys("ismobile");
            return View();
        }

        [Validate(CheckApp = false)]
        public IActionResult Tree()
        {
            ViewData["query"] = "appid=" + Request.Querys("appid") + "rf_appopenmodel=" + Request.Querys("rf_appopenmodel") + "&tabid=" + Request.Querys("tabid") + "&isselect=" + Request.Querys("isselect") + "&ismobile=" + Request.Querys("ismobile");
            ViewData["appid"] = Request.Querys("appid");
            return View();
        }

        [Validate(CheckApp = false)]
        public string Tree1()
        {
            Guid userId = Current.UserId;
            if (userId.IsEmptyGuid())
            {
                userId = Current.EnterpriseWeiXinUserId;
            }
            return new Business.UserFile().GetUserDirectoryJSON(userId, isSelect:"1".Equals(Request.Querys("isselect")));
        }

        [Validate(CheckApp = false)]
        public string TreeRefresh()
        {
            string dir = Request.Querys("refreshid");
            if (dir.IsNullOrWhiteSpace())
            {
                return "[]";
            }
            Guid userId = Current.UserId;
            if (userId.IsEmptyGuid())
            {
                userId = Current.EnterpriseWeiXinUserId;
            }
            return new Business.UserFile().GetUserDirectoryJSON(userId, dir.DESDecrypt(), "1".Equals(Request.Querys("isselect")));
        }

        [Validate(CheckApp = false)]
        public IActionResult List()
        {
            Guid userId = Current.UserId;
            if (userId.IsEmptyGuid())
            {
                userId = Current.EnterpriseWeiXinUserId;
            }
            string id = Request.Querys("id");
            string query = "appid=" + Request.Querys("appid") + "rf_appopenmodel=" + Request.Querys("rf_appopenmodel") + "&tabid=" + Request.Querys("tabid") + "&isselect=" + Request.Querys("isselect") + "&ismobile=" + Request.Querys("ismobile");
            ViewData["queryString"] = Request.UrlQuery();
            ViewData["id"] = id;
            ViewData["appid"] = Request.Querys("appid");
            ViewData["isselect"] = Request.Querys("isselect");//是否是选择附件
            ViewData["ismobile"] = Request.Querys("ismobile");
            ViewData["path"] = Business.UserFile.GetLinkPath(id.DESDecrypt(), userId, query);
            return View();
        }

        [Validate(CheckApp = false)]
        public string QueryList()
        {
            Business.UserFile userFile = new Business.UserFile();
            string path = Request.Querys("id").DESDecrypt();
            string sidx = Request.Forms("sidx");
            string sord = Request.Forms("sord");
            string searchWord = Request.Forms("searchword");
            bool isSelect = "1".Equals(Request.Querys("isselect"));
            var ps = userFile.GetSubDirectoryAndFiles(path, Current.UserIdOrWeiXinId, searchWord, sidx, sord.EqualsIgnoreCase("asc") ? 0 : 1);
            string query = "&appid=" + Request.Querys("appid") + "rf_appopenmodel=" + Request.Querys("rf_appopenmodel") + "&tabid=" + Request.Querys("tabid") + "&isselect=" + Request.Querys("isselect") + "&ismobile=" + Request.Querys("ismobile");
            JArray jArray = new JArray();
            foreach (var p in ps)
            {
                string id = isSelect ? Business.UserFile.GetRelativePath(p.Item2).DESEncrypt()
                    : p.Item2.Replace("\\", "/").DESEncrypt();
                string name = string.Empty;
                if (p.Item4 == 0)//文件夹
                {
                    name = "<a class=\"blue\" href=\"List?id=" + (path + "/" + p.Item1).DESEncrypt() + query + "\">" + p.Item1 + "</a>";
                }
                else
                {
                    name = "<a class=\"blue\" href=\"" + Url.Content("~/RoadFlowCore/Controls/ShowFile?fullpath=1&file=" + p.Item2.DESEncrypt()) + "\" target=\"_blank\">" + p.Item1 + "</a>";
                }
                JObject jObject = new JObject
                {
                    { "id", id },
                    { "Name", name },
                    { "Name1", p.Item1 },
                    { "Date", isSelect ? p.Item3.ToShortDateTimeString() : p.Item3.ToDateTimeString() },
                    { "Type", p.Item4 == 0 ? "文件夹" : "文件" },
                    { "Size", p.Item5 == 0 ? "" : p.Item5.ToFileSize()  }
                };
                jArray.Add(jObject);
            }
            return jArray.ToString(Newtonsoft.Json.Formatting.None);
        }

        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string AddDir()
        {
            string DirName = Request.Form["DirName"];
            if (DirName.IsNullOrWhiteSpace())
            {
                return "文件夹名称不能为空!";
            }
            string id = Request.Querys("id");
            string basePath = id.DESDecrypt();
            var dirPath = basePath + "/" + DirName;
            if (Directory.Exists(dirPath))
            {
                return "文件夹已经存在!";
            }
            try
            {
                Directory.CreateDirectory(dirPath);
                return "1";
            }
            catch(IOException err)
            {
                return err.Message;
            }
        }

        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string Delete()
        {
            string[] files = Request.Forms("files").Split(',');
            try
            {
                foreach (string file in files)
                {
                    string path = file.DESDecrypt();
                    if (!Business.UserFile.HasAccess(path, Current.UserId))
                    {
                        continue;
                    }
                    if (Directory.Exists(path))
                    {
                        Directory.Delete(path);
                    }
                    else if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                }
                return "删除成功!";
            }
            catch (IOException err)
            {
                return err.Message;
            }
        }

        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string ReName()
        {
            string file = Request.Forms("file");
            string newname = Request.Forms("newname");
            if (newname.IsNullOrWhiteSpace())
            {
                return "要重命名的名称为空!";
            }
            if (file.IsNullOrWhiteSpace())
            {
                return "文件为空";
            }
            string msg = Business.UserFile.ReName(file.DESDecrypt(), newname);
            return msg;
        }

        [Validate(CheckApp = false)]
        public IActionResult MoveTo()
        {
            ViewData["appid"] = Request.Querys("appid");
            ViewData["queryString"] = Request.UrlQuery();
            return View();
        }

        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string MoveToSave()
        {
            string movetodir = Request.Forms("movetodir");
            string[] movedir = Request.Querys("movedir").Split(',');
            if (movedir.Length == 0)
            {
                return "没有要移动的文件或文件夹!";
            }
            if (movetodir.IsNullOrWhiteSpace())
            {
                return "要移动到的文件夹为空!";
            }
            List<string> dirs = new List<string>();
            foreach (string dir in movedir)
            {
                dirs.Add(dir.DESDecrypt());
            }
            string msg = Business.UserFile.MoveTo(dirs.ToArray(), movetodir.DESDecrypt());
            return msg;
        }

        [Validate(CheckApp = false)]
        public IActionResult Share()
        {
            ViewData["appid"] = Request.Querys("appid");
            ViewData["queryString"] = Request.UrlQuery();
            ViewData["sharedir"] = Request.Forms("sharedir");
            return View();
        }

        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string ShareSave()
        {
            string ShareUser = Request.Forms("ShareUser");
            string sharedir = Request.Forms("sharedir");
            string ExpireDate = Request.Forms("ExpireDate");
            string NoExpireDate = Request.Forms("NoExpireDate");
            if (sharedir.IsNullOrWhiteSpace() || ShareUser.IsNullOrWhiteSpace())
            {
                return "要分享的目录文件或人员为空!";
            }
            DateTime? expireTime = new DateTime?();
            if ("1".Equals(NoExpireDate))//如果永久有效则设置为最大日期
            {
                expireTime = DateTime.MaxValue;
            }
            else if (ExpireDate.IsDateTime(out DateTime dateTime))
            {
                expireTime = dateTime;
            }
            if (!expireTime.HasValue)
            {
                return "请设置有效期!";
            }
            int i = new Business.UserFileShare().Share(sharedir, ShareUser, Current.UserId, expireTime.Value);
            return "1";
        }

        [Validate(CheckApp = false)]
        public IActionResult MyShare()
        {
            ViewData["queryString"] = Request.UrlQuery();
            return View();
        }

        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string QueryMyShare()
        {
            string FileName = Request.Forms("FileName");
            string sidx = Request.Forms("sidx");
            string sord = Request.Forms("sord");

            int size = Tools.GetPageSize();
            int number = Tools.GetPageNumber();
            string order = (sidx.IsNullOrEmpty() ? "ShareDate" : sidx) + " " + (sord.IsNullOrEmpty() ? "ASC" : sord);
            Business.UserFileShare userFileShare = new Business.UserFileShare();
            var shares = userFileShare.GetMySharePagerList(out int count, size, number, Current.UserId, FileName, order);
            JArray jArray = new JArray();
            foreach (System.Data.DataRow dr in shares.Rows)
            {
                DateTime ExpireDate = dr["ExpireDate"].ToString().ToDateTime();
                string FileId = dr["FileId"].ToString();
                string path = FileId.DESDecrypt();
                string type = string.Empty;
                string fileName = string.Empty;
                string query = "&appid=" + Request.Querys("appid") + "rf_appopenmodel=" + Request.Querys("rf_appopenmodel") + "&tabid=" + Request.Querys("tabid") + "&isselect=" + Request.Querys("isselect") + "&ismobile=" + Request.Querys("ismobile");
                if (System.IO.File.Exists(path))
                {
                    type = "文件";
                    fileName = "<a target=\"_blank\" href=\"" + Url.Content("~/RoadFlowCore/Controls/ShowFile?fullpath=1&file=" + FileId) + "\">" + dr["FileName"].ToString() + "</a>";
                }
                else if (Directory.Exists(path))
                {
                    type = "文件夹";
                    fileName = "<a href=\"javascript:;\" onclick=\"showDir('" + Url.Content("~/RoadFlowCore/UserFile/") + "ShareDirList?id=" + FileId + query + "', '" + FileId + "');\">" + dr["FileName"].ToString() + "</a>";
                }
                JObject jObject = new JObject
                {
                    { "id", FileId },
                    { "FileName", fileName },
                    { "ShareDate", dr["ShareDate"].ToString().ToDateTime().ToDateTimeString() },
                    { "ExpireDate", ExpireDate.Year == DateTime.MaxValue.Year ? "永久有效" : ExpireDate.ToDateTimeString() },
                    { "Type", type}
                };
                jArray.Add(jObject);
            }
            return "{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}";
        }

        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string DeleteShare()
        {
            string[] files = Request.Forms("files").Split(',');
            Business.UserFileShare userFileShare = new Business.UserFileShare();
            foreach (string file in files)
            {
                userFileShare.DeleteByFileId(file);
            }
            return "1";
        }

        [Validate(CheckApp = false)]
        public IActionResult ShareMy()
        {
            ViewData["queryString"] = Request.UrlQuery();
            return View();
        }

        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string QueryShareMy()
        {
            string FileName = Request.Forms("FileName");
            string sidx = Request.Forms("sidx");
            string sord = Request.Forms("sord");

            int size = Tools.GetPageSize();
            int number = Tools.GetPageNumber();
            string order = (sidx.IsNullOrEmpty() ? "ShareDate" : sidx) + " " + (sord.IsNullOrEmpty() ? "ASC" : sord);
            Business.UserFileShare userFileShare = new Business.UserFileShare();
            var shares = userFileShare.GetShareMyPagerList(out int count, size, number, Current.UserId, FileName, order);
            JArray jArray = new JArray();
            foreach (System.Data.DataRow dr in shares.Rows)
            {
                DateTime ExpireDate = dr["ExpireDate"].ToString().ToDateTime();
                string FileId = dr["FileId"].ToString();
                string path = FileId.DESDecrypt();
                string type = string.Empty;
                string fileName = string.Empty;
                string query = "&appid=" + Request.Querys("appid") + "rf_appopenmodel=" + Request.Querys("rf_appopenmodel") + "&tabid=" + Request.Querys("tabid") + "&isselect=" + Request.Querys("isselect") + "&ismobile=" + Request.Querys("ismobile");
                if (System.IO.File.Exists(path))
                {
                    type = "文件";
                    fileName = "<a target=\"_blank\" href=\"" + Url.Content("~/RoadFlowCore/Controls/ShowFile?fullpath=1&checkshare=1&file=" + (path + "?" + Current.UserIdOrWeiXinId).DESEncrypt()) + "\">" + dr["FileName"].ToString() + "</a>";
                }
                else if (Directory.Exists(path))
                {
                    type = "文件夹";
                    fileName = "<a href=\"javascript:;\" onclick=\"showDir('" + Url.Content("~/RoadFlowCore/UserFile/") + "ShareDirList?id=" + FileId + query + "', '" + FileId + "');\">" + dr["FileName"].ToString() + "</a>";
                }
                JObject jObject = new JObject
                {
                    { "id", FileId },
                    { "FileName", fileName },
                    { "ShareDate", dr["ShareDate"].ToString().ToDateTime().ToDateTimeString() },
                    { "ExpireDate", ExpireDate.Year == DateTime.MaxValue.Year ? "永久有效" : ExpireDate.ToDateTimeString() },
                    { "Type", type}
                };
                jArray.Add(jObject);
            }
            return "{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}";
        }

        [Validate(CheckApp = false)]
        public IActionResult ShareDirList()
        {
            string id = Request.Querys("id");
            string fileid = Request.Querys("fileid");
            string query = "&fileid="+ fileid + "&appid=" + Request.Querys("appid") + "rf_appopenmodel=" + Request.Querys("rf_appopenmodel") + "&tabid=" + Request.Querys("tabid") + "&isselect=" + Request.Querys("isselect") + "&ismobile=" + Request.Querys("ismobile");
            ViewData["queryString"] = Request.UrlQuery();
            ViewData["path"] = Business.UserFile.GetLinkShparePath(id.DESDecrypt(), fileid.DESDecrypt(), query);
            return View();
        }

        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string QueryShareDirList()
        {
            Business.UserFile userFile = new Business.UserFile();
            string path = Request.Querys("id").DESDecrypt();
            string sidx = Request.Forms("sidx");
            string sord = Request.Forms("sord");
            string searchWord = Request.Forms("searchword");
            string fileid = Request.Querys("fileid");

            //检查是否可以查看分享文件夹
            if (!new Business.UserFileShare().IsAccess(fileid, Current.UserIdOrWeiXinId))
            {
                return "[]";
            }

            bool isSelect = "1".Equals(Request.Querys("isselect"));
            var ps = userFile.GetSubDirectoryAndFiles(path, Guid.Empty, searchWord, sidx, sord.EqualsIgnoreCase("asc") ? 0 : 1);
            string query = "&appid=" + Request.Querys("appid") + "rf_appopenmodel=" + Request.Querys("rf_appopenmodel") + "&tabid=" + Request.Querys("tabid") + "&isselect=" + Request.Querys("isselect") + "&ismobile=" + Request.Querys("ismobile");
            JArray jArray = new JArray();
            foreach (var p in ps)
            {
                string id = isSelect ? Business.UserFile.GetRelativePath(p.Item2).DESEncrypt()
                    : p.Item2.Replace("\\", "/").DESEncrypt();
                string name = string.Empty;
                if (p.Item4 == 0)//文件夹
                {
                    name = "<a class=\"blue\" href=\"ShareDirList?id=" + (path + "/" + p.Item1).DESEncrypt() + query + "&fileid="+ fileid + "\">" + p.Item1 + "</a>";
                }
                else
                {
                    name = "<a target=\"_blank\" href=\"" + Url.Content("~/RoadFlowCore/Controls/ShowFile?fullpath=1&checkshare=1&file=" + (p.Item2 + "?" + Current.UserIdOrWeiXinId + "?" + fileid).DESEncrypt()) + "\">" + p.Item1 + "</a>";
                }
                JObject jObject = new JObject
                {
                    { "id", id },
                    { "Name", name },
                    { "Name1", p.Item1 },
                    { "Date", isSelect ? p.Item3.ToShortDateTimeString() : p.Item3.ToDateTimeString() },
                    { "Type", p.Item4 == 0 ? "文件夹" : "文件" },
                    { "Size", p.Item5 == 0 ? "" : p.Item5.ToFileSize()  }
                };
                jArray.Add(jObject);
            }
            return jArray.ToString(Newtonsoft.Json.Formatting.None);
        }
    }
    
}